<template>
  <!-- 歌词路由 -->
  <div id="lyric">
    <LyricPhoto></LyricPhoto>
    <LyricDetail></LyricDetail>
    <SongComment @change-page="changePage"></SongComment>
  </div>
</template>

<script>
import {
  computed,
  defineComponent,
  onMounted,
  provide,
  reactive,
  ref,
  watch,
} from "vue";
import { mapGetters, useStore } from "vuex";
import LyricPhoto from "@/components/lyric/LyricPhoto.vue";
import LyricDetail from "@/components/lyric/LyricDetail.vue";
import SongComment from "@/components/lyric/SongComment.vue";
import { handleSongLyric, handleSongComment } from "@/network/lyric/lyric.js";
export default defineComponent({
  name: "Lyric",
  components: {
    LyricPhoto,
    LyricDetail,
    SongComment,
  },
  setup() {
    const store = useStore();
    let currentPlaySong = computed(
      mapGetters(["getCurrentPlaySong"]).getCurrentPlaySong.bind({
        $store: store,
      })
    );
    let currentPlaySongCurrentTime = computed(
      mapGetters(["getPlaySongCurrentTime"]).getPlaySongCurrentTime.bind({
        $store: store,
      })
    );
    let data = reactive({
      songCommentParams: {
        id: 0,
        offset: 0,
        limit: 20,
      },
    });
    let lyric = ref(""); // 歌词数组
    let songComments = ref({}); // 歌曲评论
    provide("currentPlaySong", currentPlaySong);
    provide("lyric", lyric);
    provide("currentPlaySongCurrentTime", currentPlaySongCurrentTime);
    provide("songComments", songComments);

    onMounted(() => {
      if (Object.keys(currentPlaySong.value).length !== 0) {
        getSongLyric(currentPlaySong.value.id);
        data.songCommentParams.id = currentPlaySong.value.id;
        getSongComment(data.songCommentParams);
      }
    });

    watch(
      () => currentPlaySong.value,
      () => {
        if (Object.keys(currentPlaySong.value).length !== 0) {
          getSongLyric(currentPlaySong.value.id);
          data.songCommentParams.id = currentPlaySong.value.id;
          getSongComment(data.songCommentParams);
        }
      }
    );

    // 获取歌词
    let getSongLyric = async (id) => {
      let res = await handleSongLyric(id);
      lyric.value = res.lrc.lyric;
    };

    // 获取歌曲评论
    let getSongComment = async (params) => {
      let res = await handleSongComment(params);
      if (res.hotComments) {
        songComments.value.hotComments = res.hotComments;
      }
      songComments.value.comments = res.comments;
      songComments.value.total = res.total;
    };

    // 子组件评论区域改变页码事件
    let changePage = (page) => {
      data.songCommentParams.offset = (page - 1) * 20;
      getSongComment(data.songCommentParams);
    };
    return { changePage };
  },
});
</script>
<style scoped>
#lyric {
  width: 100%;
  height: calc(100vh - 80px - 65px);
  overflow-y: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2c2c2d;
}
</style>
